package com.fdb.efp.nls.service.impl;

import com.fdb.basic.framework.core.exception.BizException;
import com.fdb.efp.console.common.psd.PsdConstantSet;
import com.fdb.efp.nls.common.UploadFileConstant;
import com.fdb.efp.nls.common.bo.UpLoadFileVO;
import com.fdb.efp.nls.service.facade.ContractFileService;
import com.fdb.efp.nls.service.facade.UpLoadFileService;
import com.fdb.efp.esb.common.constant.EsbBizEnums;
import com.fdb.efp.nls.service.facade.AccLoanService;
import com.fdb.efp.nls.service.vo.AccLoanVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Objects;

@Service("contractFileService")
public class ContractFileServiceImpl implements ContractFileService {

    private static Logger logger = LoggerFactory.getLogger(ContractFileServiceImpl.class);

    @Value("${psd_cont_save_path}")
    private String psdContSavePath;

    @Autowired
    private UpLoadFileService upLoadFileService;

    @Autowired
    private AccLoanService accLoanService;

    @Override
    public String downContractFile(String prdId, String contractType, String applySeq) throws Exception {
        //普税贷产品
        if (PsdConstantSet.prdId.equals(prdId)) {
            return downPsdContractFile(contractType, applySeq);
        }
        throw new BizException(EsbBizEnums.RetCodeEnum.CPXXJYBTG.getVALUE(), "暂不支持该产品的合同下载");
    }

    /**
     * 普税贷合同下载
     * @param contractType 合同类型 1 授信合同-脱敏版 2 借款合同-脱敏版 5 授权书-脱敏版
     * @param applySeq 申请流水号
     * @return String base64的合同文件
     * @throws Exception 异常信息
     */
    private String downPsdContractFile(String contractType, String applySeq) throws Exception {
        //授信合同下载
        if ("1".equals(contractType)) {
            //根据流水号查询普税局贷授信合同上传记录
            UpLoadFileVO upLoadFileParam = new UpLoadFileVO();
            upLoadFileParam.setApplySeq(applySeq);
            upLoadFileParam.setImageType(PsdConstantSet.PSD_SX_CONT_TM_TYPE);
            UpLoadFileVO upLoadFileVO = upLoadFileService.queryUploadFileByApplySeqAndImageType(upLoadFileParam);
            if (upLoadFileVO != null&&StringUtils.isNotBlank(upLoadFileVO.getApplySeq())) {
                //查询影像系统记录
                String sxContFilePath = UploadFileConstant.downFileFromImageSys(upLoadFileVO, "/psd");
                if (StringUtils.isNotEmpty(sxContFilePath)) {
                    //将数据转为base64返回
                    return fileToBase64Str(sxContFilePath);
                }
            }
            //查看本地文件记录
            return fileToBase64Str(psdContSavePath + applySeq + "/" + applySeq + "_tmsxcont.pdf");
        }
        if ("2".equals(contractType)) {
            //根据流水号(借据号)查询普税贷借款合同上传记录
            //查询出借据信息
            AccLoanVO pkParam = new AccLoanVO();
            pkParam.setBillNo(applySeq);
            AccLoanVO accLoanVO = accLoanService.queryByPk(pkParam);
            if (Objects.isNull(accLoanVO)) {
                throw new Exception("获取借据信息为空");
            }
            applySeq = accLoanVO.getApplySeq();
            UpLoadFileVO upLoadFileParam = new UpLoadFileVO();
            upLoadFileParam.setApplySeq(applySeq);
            upLoadFileParam.setImageType(PsdConstantSet.PSD_YX_CONT_TM_TYPE);
            UpLoadFileVO upLoadFileVO = upLoadFileService.queryUploadFileByApplySeqAndImageType(upLoadFileParam);
            if (upLoadFileVO != null&&StringUtils.isNotBlank(upLoadFileVO.getApplySeq())) {
                //查询影像系统记录
                String sxContFilePath = UploadFileConstant.downFileFromImageSys(upLoadFileVO, "/psd");
                if (StringUtils.isNotEmpty(sxContFilePath)) {
                    //将数据转为base64返回
                    return fileToBase64Str(sxContFilePath);
                }
            }
            //查看本地文件记录
            return fileToBase64Str(psdContSavePath + applySeq + "/" + applySeq + "_tmdkcont.pdf");
        }
        if ("5".equals(contractType)) {
            //根据流水号查询普税局贷授信合同上传记录
            UpLoadFileVO upLoadFileParam = new UpLoadFileVO();
            upLoadFileParam.setApplySeq(applySeq);
            upLoadFileParam.setImageType(PsdConstantSet.PSD_FILE_TM_TYPE_03);
            UpLoadFileVO upLoadFileVO = upLoadFileService.queryUploadFileByApplySeqAndImageType(upLoadFileParam);
            if (upLoadFileVO != null&&StringUtils.isNotBlank(upLoadFileVO.getApplySeq())) {
                //查询影像系统记录
                String sxContFilePath = UploadFileConstant.downFileFromImageSys(upLoadFileVO, "/psd");
                if (StringUtils.isNotEmpty(sxContFilePath)) {
                    //将数据转为base64返回
                    return fileToBase64Str(sxContFilePath);
                }
            }
            //查看本地文件记录
            return fileToBase64Str(psdContSavePath + applySeq + "/" + applySeq + "_tmsqs.pdf");
        }
        throw new Exception("暂不支持的合同类型");
        //用信合同下载
    }


    private String fileToBase64Str(String filePath) throws Exception {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new Exception("查询不到文件数据，请稍后再试");
        }
        byte[] bytes = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
        return Base64.getEncoder().encodeToString(bytes);
    }

}
